package com.roncoo.education.db.service;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.roncoo.education.api.request.PageBaseRequest;
import com.roncoo.education.db.dao.MyHistoryDao;
import com.roncoo.education.db.entity.MyHistory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class MyHistoryService {

    @Resource
    private MyHistoryDao myHistoryDao;

    public Map<String,String> saveHistory(Long userId, Long historyId,Integer historyType){
        MyHistory query = new MyHistory();
        query.setMemberId(userId);
        query.setHistoryId(historyId);
        query.setHistoryType(historyType);
        query.setOrderClause(" id desc limit 1");
        List<MyHistory> list =myHistoryDao.findByBean(query);
        if(CollUtil.isNotEmpty(list)) {
            Map<String,String> ret = new HashMap<>();
            ret.put("isError", "success");
            ret.put("code", "1");
            return ret;
        }
        MyHistory history = new MyHistory();
        history.setMemberId(userId);
        history.setHistoryId(historyId);
        history.setHistoryType(historyType);
        history.setCreateTime(new Date());

        myHistoryDao.insert(history);
        Long nid = history.getId();
        Map<String,String> ret = new HashMap<>();
        ret.put("isError", "success");
        ret.put("id", String.valueOf(nid));
        ret.put("code", "1");
        return ret;
    }

    public PageInfo<MyHistory> getHistoryPages(Long userId, PageBaseRequest req){
        if(req == null) return null;
        int pageNum = req.getPageNum();
        int pageSize = req.getCount();
        if (req.getPageNum() == null || req.getPageNum() <= 0 || req.getCount() == null) {
            pageNum = 1;
            pageSize = 20;
        }
        MyHistory query = new MyHistory();
        query.setMemberId(userId);
        PageHelper.startPage(pageNum, pageSize);
        List<MyHistory> newsList = myHistoryDao.selectMyHistoryList(query);
        return new PageInfo<>(newsList);
    }
}
